package com.hrb.monkey.task;

import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hrb.monkey.UserAdapter;
import com.hrb.monkey.record.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoadInfoGson extends AsyncTask<String,Integer,Integer> {
    private static  List userList=new ArrayList();;

    private RecyclerView recyclerView;
    private Unbinder unbinder;

    LinearLayoutManager linearLayoutManager;
    private  boolean result=false;

    public LoadInfoGson(RecyclerView recyclerView, LinearLayoutManager linearLayoutManager) {
        this.recyclerView = recyclerView;
        this.linearLayoutManager = linearLayoutManager;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Integer doInBackground(String... strings) {
        String url = strings[0];
        //String url = "https://www.easy-mock.com/mock/5a4d85d3e5f9cd651a7fbe77/test/userInfo";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("", "链接失败: " + e);
                result=false;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject value=new JSONObject(response.body().string());
                    userList.addAll(parseJSONWithGSON(value.getString("data")));
                    result=true;
                    publishProgress(1);
                } catch (JSONException e) {
                    result=false;
                }

            }
        });
        return null;
    }
    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if(result){
            recyclerView.setLayoutManager(linearLayoutManager);
           UserAdapter userAdapter = new UserAdapter(userList);
            recyclerView.setAdapter(userAdapter);
        }
    }

    private List parseJSONWithGSON(String data) {
        Gson gson = new Gson();
        List<User> list = gson.fromJson(data, new TypeToken<List<User>>() {
        }.getType());
        return list;
    }


}
